<template>
  <el-container>
    <el-main class="register-frame">
      <el-card class="register-card">
        <h2 style="text-align: center">用户注册</h2>
        <br />
        <el-form
            ref="registerForm"
            :model="registerData"
            :rules="rules"
            label-position="left"
            label-align="left"
            label-width="80px"
            @submit.prevent="submitRegister"
        >
          <!-- 用户名 -->
          <el-form-item label="用户名" prop="username">
            <el-input
                v-model="registerData.username"
                @input="checkUsernameUnique"
            />
            <span v-if="usernameCheckStatus === 'checking'" class="check-status">正在检查...</span>
            <span v-else-if="usernameCheckStatus === 'exists'" class="check-status error">该用户名已存在</span>
            <span v-else-if="usernameCheckStatus === 'available'" class="check-status success">用户名可用</span>
          </el-form-item>

          <!-- 昵称 -->
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="registerData.nickname" />
          </el-form-item>

          <!-- 密码 -->
          <el-form-item label="密码" prop="password">
            <el-input
                v-model="registerData.password"
                type="password"
                show-password
            />
          </el-form-item>

          <!-- 电话 -->
          <el-form-item label="电话" prop="phone">
            <div style="display: flex; flex-direction: column;">
              <div style="display: flex; justify-content: space-between;">
                <el-input v-model="registerData.phone" @input="debouncedCheckPhone" />
                <el-button
                    style="margin-left: 10px;"
                    type="success"
                    @click="handleSendVerificationCode"
                    :disabled="!canSendCode"
                >{{
                    sendingCode ? `重新发送(${countdown}s)` : "发送验证码"
                  }}</el-button>
              </div>
              <span v-if="phoneCheckStatus === 'checking'" class="check-status">正在检查...</span>
              <span v-else-if="phoneCheckStatus === 'available'" class="check-status error">该电话已被注册</span>
              <span v-else-if="phoneCheckStatus === 'exists'" class="check-status success">电话可用</span>
            </div>
          </el-form-item>

          <!-- 验证码 -->
          <el-form-item label="验证码" prop="verificationCode">
            <el-input
                v-model="registerData.verificationCode"
                placeholder="请输入收到的验证码"
            />
          </el-form-item>

          <!-- 头像上传 -->
          <el-form-item label="头像上传" prop="avatar">
            <el-upload
                action="#"
                list-type="picture-card"
                :auto-upload="false"
                :on-change="handleAvatarUpload"
                :limit="1"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <br />

          <!-- 提交按钮 -->
          <div style="display: flex; justify-content: space-around; flex-direction: row;">
            <el-button
                size="large"
                style="width: 100px;"
                type="primary"
                native-type="submit"
                :loading="isSubmitting"
            >
              立即注册
            </el-button>
            <el-button @click="router.back()" size="large" style="width: 80px;" type="danger">返回</el-button>
          </div>
        </el-form>
      </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import { reactive, ref, computed } from "vue";
import { ElMessage } from "element-plus";
import router from "@/router";
import userRegister from "@/api/modules/userRegister";
import { debounce } from 'lodash-es';

// 表单数据
const registerData = reactive({
  username: "",
  nickname: "",
  password: "",
  phone: "",
  verificationCode: "",
  avatar: null,
});

// 表单引用
const registerForm = ref(null);

// 检查状态
const usernameCheckStatus = ref("");
const phoneCheckStatus = ref("");

// 验证码相关
const sendingCode = ref(false);
const countdown = ref(60);
let countdownTimer = null;

// 提交状态
const isSubmitting = ref(false);

// 计算属性：是否可以发送验证码
const canSendCode = computed(() => {
  return registerData.phone && phoneCheckStatus.value === 'exists';
});

// 实际检查用户名唯一性
const checkUsernameUnique = async () => {
  const { username } = registerData;
  if (!username.trim()) return;
  usernameCheckStatus.value = "checking";
  try {
    const res = await userRegister.checkUsernameUnique(username);
    console.log(res); // 打印响应数据以便调试
    // 根据 data 字段的值来设置 usernameCheckStatus
    if (res.data) {
      usernameCheckStatus.value = "exists"; // 用户名已存在
    } else {
      usernameCheckStatus.value = "available"; // 用户名可用
    }
  } catch (error) {
    console.error("检查用户名失败", error);
    usernameCheckStatus.value = "";
    ElMessage.error("无法检查用户名");
  }
};

// 实际检查电话唯一性
const checkPhoneUnique = async () => {
  const {phone} = registerData;
  if (!phone.trim()) return;

  // 验证手机号格式
  if (!/^1[3-9]\d{9}$/.test(phone)) {
    phoneCheckStatus.value = "";
    return;
  }

  phoneCheckStatus.value = "checking";
  try {
    const res = await userRegister.checkPhoneUnique(phone);
    console.log(res);
    phoneCheckStatus.value = res ? "exists" : "available";
  } catch (error) {
    console.error("检查电话失败", error);
    phoneCheckStatus.value = "";
    ElMessage.error("无法检查电话");
  }
};

// 处理发送验证码逻辑
const handleSendVerificationCode = async () => {
  try {
    // 验证表单
    await registerForm.value.validateField(['username', 'nickname', 'password']);

    // 检查用户名是否可用
    if (usernameCheckStatus.value !== 'available') {
      ElMessage.warning("请先检查用户名是否可用");
      return;
    }

    // 检查电话号码是否可用
    if (phoneCheckStatus.value !== 'exists') {
      console.log("000"+phoneCheckStatus.value)
      ElMessage.warning("请先检查电话号码是否可用");
      return;
    }

    // 清除之前的定时器
    if (countdownTimer) {
      clearInterval(countdownTimer);
    }

    sendingCode.value = true;
    countdown.value = 60;

    countdownTimer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(countdownTimer);
        sendingCode.value = false;
      }
    }, 1000);

    // 调用API发送验证码
    await userRegister.sendSmsCode(registerData.phone);
    ElMessage.success("验证码已发送，请注意查收");
  } catch (error) {
    console.error("发送验证码失败", error);
    if (error !== 'cancel') {
      ElMessage.error(error.message || "发送验证码失败，请重试");
    }
    if (countdownTimer) {
      clearInterval(countdownTimer);
    }
    sendingCode.value = false;
    countdown.value = 60;
  }
};

// 验证短信验证码
const verifySmsCode = async () => {
  try {
    const response = await userRegister.verifySmsCode(
        registerData.phone,
        registerData.verificationCode
    );
    console.log("手机验证码", response.code);

    if (response.code === 200) {
      return true;
    } else {
      ElMessage.error(response.message || "验证码验证失败");
      return false;
    }
  } catch (error) {
    console.error("验证码验证失败:", error);
    ElMessage.error(error.response?.data?.message || "验证码验证失败");
    return false;
  }
};

// 表单规则
const rules = {
  username: [
    {required: true, message: "请输入用户名", trigger: "blur"},
    {min: 3, max: 15, message: "用户名长度应在3-15个字符之间", trigger: "blur"}
  ],
  nickname: [
    {required: true, message: "请输入昵称", trigger: "blur"},
    {min: 2, max: 10, message: "昵称长度应在2-10个字符之间", trigger: "blur"}
  ],
  password: [
    {required: true, message: "请输入密码", trigger: "blur"},
    {min: 6, message: "密码至少需要6个字符", trigger: "blur"}
  ],
  phone: [
    {required: true, message: "请输入电话号码", trigger: "blur"},
    {
      validator: (rule, value, callback) => {
        if (!/^1[3-9]\d{9}$/.test(value)) {
          callback(new Error("请输入有效的手机号码"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  verificationCode: [
    {required: true, message: "请输入验证码", trigger: "blur"}
  ]
};

// 头像上传处理
const handleAvatarUpload = (file) => {
  registerData.avatar = file.raw;
};

// 提交注册表单
const submitRegister = async () => {
  try {
    isSubmitting.value = true;

    // 验证整个表单
    await registerForm.value.validate();

    // 检查电话号码是否可用
    if (phoneCheckStatus.value !== 'exists') {
      ElMessage.warning("请先检查电话号码是否可用");
      return;
    }

    // 检查验证码是否填写
    if (!registerData.verificationCode) {
      ElMessage.warning("请输入验证码");
      return;
    }

    // 验证短信验证码
    const isCodeValid = await verifySmsCode();
    console.log("验证码验证结果：", isCodeValid);
    if (!isCodeValid) {
      return;
    }

    // 构建注册数据
    const userData = {
      userName: registerData.username,
      nickname: registerData.nickname,
      password: registerData.password,
      contact: registerData.phone,
      verificationCode: registerData.verificationCode
    };

    // 提交注册
    await userRegister.register(userData, registerData.avatar);
    ElMessage.success("注册成功！");
    router.push('/login');
  } catch (error) {
    console.error('Registration failed:', error);
    ElMessage.error(error.response?.data?.message || "注册失败，请重试");
  } finally {
    isSubmitting.value = false;
  }
};


// 防抖处理
const debouncedCheckPhone = debounce(checkPhoneUnique, 500);
</script>


<style scoped>
.register-frame {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url("https://img.neptech.net/i/2025/06/17/iiwdzv.webp");
  background-size: cover;
  gap: 20px;
}

.register-card {
  max-width: 450px;
  margin: auto;
  padding: 20px;
}

.el-form {
  padding: 20px;
  box-sizing: border-box;
  width: 100%;
}

.check-status {
  font-size: 12px;
  margin-top: 5px;
  display: inline-block;
}

.check-status.error {
  color: #f56c6c;
}

.check-status.success {
  color: #67c23a;
}
</style>
